var luaUtil = require('./luaUtil');
var async = require('async');
var moment = require('moment');

var CommonUtil = require('../../../../../common/util/CommonUtil');
var YjxOrgRModel = require('../../../../../common/yjxMysql/mapping/YjxOrgRModel');
var YjxOrgModel = require('../../../../../common/yjxMysql/mapping/YjxOrgModel');
var YjxThirdPartyUserModel = require('../../../../../common/yjxMysql/mapping/YjxThirdPartyUserModel');
var YjxActivityModel = require('../../../../../common/yjxMysql/mapping/YjxActivityModel');
var YjxActUserProductModel = require('../../../../../common/yjxMysql/mapping/YjxActUserProductModel');
var YJxUserModel = require('../../../../../common/yjxMysql/mapping/YjxUserModel');
var YjxActFinanceHis = require('../../../../../common/yjxMysql/mapping/YjxActFinanceHis');
var YjxActRewardRuleModel = require('../../../../../common/yjxMysql/mapping/YjxActRewardRuleModel');
var YjxActUserReward = require('../../../../../common/yjxMysql/mapping/YjxActUserReward');
var YjxActStatsModel = require('../../../../../common/yjxMysql/mapping/YjxActStatsModel');
var YjxCouponModel = require('../../../../../common/yjxMysql/mapping/YjxCouponModel');
var YjxUserModel =  require('../../../../../common/yjxMysql/mapping/YjxUserModel');
var YjxMemberModel = require('../../../../../common/yjxMysql/mapping/YjxMemberModel');
var YjxUserPointsHisModel = require('../../../../../common/yjxMysql/mapping/YjxUserPointsHisModel');
var CONFIG = require('../../../../../common/config');
var CODE = require('../../../../../common/code');


var promoterUtil = (function () {

    function promoterUtil() {
    }

    /**
     * 给使用推荐码和推荐码拥有则发放收益
     *
     * @author 王俊
     * @date 2018-07-10
     *
     * @param options   请求参数
     * @param options.actId  活动唯一标识
     * @param callback
     *          error:  发放失败
     */
    promoterUtil.distributeIncomeForPromoterCoderUser = function (options, callback) {
        var totalTasks = [];

        // 1. 发放使用推荐码奖励
        totalTasks.push(function (callback) {
            promoterUtil.useCcodeReward(options,function (err,result) {
                var data = {};
                return callback(err,data);
            });
        });
        // 2. 发放拥有推荐码的奖励
        totalTasks.push(function (data, callback) {
            promoterUtil.ownCcodeReward(options,function (err,result) {
                return callback(err,data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            return callback(error, data);
        });
    };

    /**
     * 给使用推荐码和推荐码拥有则发放收益
     *
     * @author 王俊
     * @date 2018-07-10
     *
     * @param options   请求参数
     * @param options.actId  活动唯一标识
     * @param callback
     *          error:  发放失败
     */
    promoterUtil.useCcodeReward = function (options, callback) {

        var totalTasks = [];

        // 1. 查询活动相关信息
        totalTasks.push(function (callback) {
            var entity = new YjxActivityModel();
            entity.getSingleActivitySettingInfo(options.actId, function (error, settingInfo) {
                if(error) {
                    return callback(error, null);
                }
                var data = {};
                data.actSettingInfo = settingInfo;
                // 只有进行中和评奖中的活动才可发放推广收益
                if(data.actSettingInfo.state <20 || data.actSettingInfo.state > 30) {
                    return callback('仅进行中和评奖中的活动才可发放收益', null);
                }
                if(data.actSettingInfo.sub_reward_2 <=0) {
                    return callback('该活动未配置使用推荐码奖励', null);
                }
                return callback(error, data);
            });
        });
        // 2. 查询规则相关信息
        totalTasks.push(function (data, callback) {
            var entity = new YjxActRewardRuleModel({
                as_id : data.actSettingInfo.as_id,
                type : 21,  // 21填写推荐码奖励
                state : 10, //10有效
                del_flg : 0
            });
            entity.findFromDB(function (error, rules) {
                if(error || !rules || rules.length <=0) {
                    return callback(error || '未查询到使用推荐码奖励规则', null);
                }
                if(rules.length > 1) {
                    return callback('推荐码使用奖励, 暂不支持多条规则配置', null);
                }

                var totalPromoterReward = 0;
                for(var i=0; i<rules.length; i++) {
                    var rule = rules[0];
                    totalPromoterReward += ((rule.max - rule.min + 1) * rule.reward_amt);
                }
                if (totalPromoterReward !== data.actSettingInfo.sub_reward_2) {
                    return  callback('使用推荐码奖金配置错误', null);
                }
                data.rule = rules[0];
                return callback(error, data);
            });
        });
        // 3. 查询已发放收益
        totalTasks.push(function (data, callback) {

            var entity = new YjxActUserReward({
                act_id : options.actId,
                r_type : 21, // 21填写推广码奖励
                bal_flg : 1,
                del_flg : 0,
            });
            entity.findCountFromDB(function (error, cnt) {
                if(error) return callback(error);
                data.alreadyDistributeCnt = cnt;
                return callback(null, data);
            });
        });
        // 4. 查询应发放收益
        totalTasks.push(function (data, callback) {
            var limit = data.rule.max - data.alreadyDistributeCnt;
            if(limit <=0) {
                data.products = [];
                return callback(null, data);
            }
            var entity = new YjxActivityModel();
            var opt = {
                actId : options.actId,
                limit : limit
            };
            entity.getDistributeIncomeForUserUsePromoterCodeList(opt, function (error, products) {
                if(error) {
                    return callback(error, null);
                }
                data.products = products;
                return callback(error, data);
            });
        });
        // 5. 发放未发放收益
        totalTasks.push(function (data, callback) {
            if(!data.products || data.products.length <=0) {
                return callback(null, data);
            }
            var opt = {
                products: data.products,
                rewardAmount: data.rule.reward_amt
            };
            promoterUtil.distributeIncomeWithProducts(opt, function (error, results) {
                return callback(error, data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            return callback(error, {});
        });
    };


    /**
     * 推荐码拥有者发放收益
     *
     * @author 毛凯
     * @date 2018-07-19
     *
     * @param options   请求参数
     * @param options.actId  活动唯一标识
     * @param callback
     *          error:  发放失败
     */
    promoterUtil.ownCcodeReward = function (options, callback) {

        var totalTasks = [];

        // 1. 查询活动相关信息
        totalTasks.push(function (callback) {
            var entity = new YjxActivityModel();
            entity.getSingleActivitySettingInfo(options.actId, function (error, settingInfo) {
                if(error) {
                    return callback(error, null);
                }

                var data = {};
                data.actSettingInfo = settingInfo;
                // 只有进行中和评奖中的活动才可发放推广收益
                if(data.actSettingInfo.state <20 || data.actSettingInfo.state > 30) {
                    return callback('仅进行中和评奖中的活动才可发放收益', null);
                }
                if(data.actSettingInfo.sub_reward_1 <=0) {
                    return callback('该活动未配置使用推荐码奖励', null);
                }
                return callback(error, data);
            });
        });
        // 2. 查询规则相关信息
        totalTasks.push(function (data, callback) {
            var entity = new YjxActRewardRuleModel({
                as_id : data.actSettingInfo.as_id,
                type : 20,  // 20发放推荐码奖励
                state : 10, //10有效
                del_flg : 0
            });
            entity.findFromDB(function (error, rules) {
                if(error || !rules || rules.length <=0) {
                    return callback(error || '未查询到发放推荐码奖励规则', null);
                }
                if(rules.length > 1) {
                    return callback('发放推荐码奖励, 暂不支持多条规则配置', null);
                }

                var totalPromoterReward = 0;
                for(var i=0; i<rules.length; i++) {
                    var rule = rules[0];
                    totalPromoterReward += ((rule.max - rule.min + 1) * rule.reward_amt);
                }
                if (totalPromoterReward !== data.actSettingInfo.sub_reward_1) {
                    return  callback('使用推荐码奖金配置错误', null);
                }
                data.rule = rules[0];
                return callback(error, data);
            });
        });
        // 3. 查询已发放收益
        totalTasks.push(function (data, callback) {

            var entity = new YjxActUserReward({
                act_id : options.actId,
                r_type : 20, // 20发放推荐码奖励
                bal_flg : 1,
                del_flg : 0,
            });
            entity.findCountFromDB(function (error, cnt) {
                if(error) return callback(error);
                data.alreadyDistributeCnt = cnt;
                return callback(null, data);
            });
        });
        // 4. 查询应发放收益
        totalTasks.push(function (data, callback) {
            var limit = data.rule.max - data.alreadyDistributeCnt;
            if(limit <=0) {
                data.products = [];
                return callback(null, data);
            }
            var entity = new YjxActivityModel();
            var opt = {
                actId : options.actId,
                limit : limit
            };
            entity.getOwnCcodeUserPromoterCodeList(opt, function (error, products) {
                if(error) {
                    return callback(error, null);
                }
                data.products = products;
                return callback(error, data);
            });
        });
        // 5. 发放未发放收益
        totalTasks.push(function (data, callback) {
            if(!data.products || data.products.length <=0) {
                return callback(null, data);
            }
            var opt = {
                products: data.products,
                rewardAmount: data.rule.reward_amt
            };
            promoterUtil.distributeOwnCcodeWithProducts(opt, function (error, results) {
                return callback(error, data);
            });
        });

        async.waterfall(totalTasks, function (error, data) {
            return callback(error, {});
        });
    };




    /**
     * 根据作品数组发放奖励
     *
     * @author 王俊
     * @date 2018-07-10*
     *
     * @param {Object} options  参数
     * @param {Number} options.rewardAmount 每个作品奖励金额
     * @param {Array} options.products  作品数组
     * @param {Number} options.products[0].act_id   该作品对应的活动 id
     * @param {Number} options.products[0].user_id  该作品对应的用户 id
     * @param {Number} options.products[0].org_id 该作品对应的用户所在的组织 id
     * @param {Number} options.products[0].valid_aup_id 发放奖励对应的作品 id
     * @param callback
     *          error
     */
    promoterUtil.distributeIncomeWithProducts = function (options, callback) {

        var totalTasks = [];
        var entity = new YjxActUserReward();
        for(var i=0; i<options.products.length; i++) {
            var t = (function (index, product) {
                return function (callback) {
                    product.reward_amount = options.rewardAmount;
                    entity.distributeUserUsePromoterCodeIncome(product, callback);
                }
            })(i, options.products[i]);
            if(t) totalTasks.push(t);
        }
        async.series(totalTasks, function (error, results) {
            return callback(error, null);
        });
    };



    /**
     * 根据作品数组发放推荐码奖励
     *
     * @author 毛凯
     * @date 2018-07-10*
     *
     * @param {Object} options  参数
     * @param {Number} options.rewardAmount 每个作品奖励金额
     * @param {Array} options.products  作品数组
     * @param {Number} options.products[0].act_id   该作品对应的活动 id
     * @param {Number} options.products[0].user_id  该作品对应的用户 id
     * @param {Number} options.products[0].uid     该作品推荐码的用户 id
     * @param {Number} options.products[0].org_id 该作品对应推荐码的用户所在的组织 id
     * @param {Number} options.products[0].valid_aup_id 发放奖励对应的作品 id
     * @param callback
     *          error
     */
    promoterUtil.distributeOwnCcodeWithProducts = function (options, callback) {

        var totalTasks = [];
        var entity = new YjxActUserReward();
        for(var i=0; i<options.products.length; i++) {
            var t = (function (index, product) {
                return function (callback) {
                    product.reward_amount = options.rewardAmount;
                    entity.distributeOwnCcodeWithProducts(product, callback);
                }
            })(i, options.products[i]);
            if(t) totalTasks.push(t);
        }
        async.series(totalTasks, function (error, results) {
            return callback(error, null);
        });
    };

    return promoterUtil;
})();

module.exports = promoterUtil;